package com.example.music_player

import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

class MusicAdapter(
    private val musicList: List<MusicFile>,
    private val activity: UserActivity
) : RecyclerView.Adapter<MusicAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val index: TextView = view.findViewById(R.id.tv_index)
        val songName: TextView = view.findViewById(R.id.tv_song_name)
        val btnLike: ImageButton = view.findViewById(R.id.btn_like)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_music, parent, false)
        return ViewHolder(view)
    }

    override fun getItemCount() = musicList.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val music = musicList[position]
        holder.index.text = "${position + 1}"
        holder.songName.text = music.name

        // 获取当前用户的喜欢列表
        val sharedPreferences = activity.getSharedPreferences("UserPreferences", Context.MODE_PRIVATE)
        val likedMusicSet = sharedPreferences.getStringSet("likedMusic", emptySet()) ?: emptySet()

        // 设置喜欢按钮的状态
        if (likedMusicSet.contains(music.uri.toString())) {
            holder.btnLike.setImageResource(R.drawable.ic_liked)
        } else {
            holder.btnLike.setImageResource(R.drawable.ic_like)
        }

        // 点击歌曲名播放音乐
        holder.itemView.setOnClickListener {
            activity.playMusicAtPosition(position)
        }

        // 喜欢按钮点击事件
        holder.btnLike.setOnClickListener {
            val editor = sharedPreferences.edit()
            val newLikedMusicSet = likedMusicSet.toMutableSet()

            if (likedMusicSet.contains(music.uri.toString())) {
                newLikedMusicSet.remove(music.uri.toString())
                holder.btnLike.setImageResource(R.drawable.ic_like)
            } else {
                newLikedMusicSet.add(music.uri.toString())
                holder.btnLike.setImageResource(R.drawable.ic_liked)
            }

            editor.putStringSet("likedMusic", newLikedMusicSet)
            editor.apply()

            activity.updateMusicList()
        }
    }
}
